import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.isHappy(19));
        System.out.println(s.isHappy(2));
    }
}


class Solution {
    public boolean isHappy(int n) {
        Set<Integer> occur = new HashSet<>();
        int cur = n;
        while(!isLast(cur)){
            if(occur.contains(cur)){
                return false;
            }
            occur.add(cur);
            int next = 0;
            while(cur != 0){
                int digit = cur % 10;
                next += digit * digit;
                cur /= 10;
            }
            cur = next;
        }
        return true;
    }

    boolean isLast(int n){
        while(n > 10){
            if(n % 10 != 0){
                return false;
            }
            n /= 10;
        }
        return n == 1;
    }
}